package com.hg.controller;



import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import com.hg.pojo.HgMallDish;
import com.hg.pojo.HgMallOrders;
import com.hg.pojo.HgMallShop;
import com.hg.pojo.dto.HgMallDishDTO;
import com.hg.service.HgMallOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class HgAdminOrderController {


    @Autowired
    private HgMallOrderService hgMallOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static int shopId;
    @GetMapping("/orderList")
    public R<Page<HgMallOrders>> getList(int currentPage, int pageSize,String appid,String orderNum,String oddNum,Integer orderStatus){
        String key = "order_" + shopId;
        redisTemplate.delete(key);
        Page<HgMallOrders> hgMallOrdersPage = null;
        hgMallOrdersPage = (Page<HgMallOrders>) redisTemplate.opsForValue().get(key);
        if (hgMallOrdersPage != null){
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrdersPage);
        }
        hgMallOrdersPage = hgMallOrderService.selectHgMallOrdersList(currentPage, pageSize,appid,orderNum,oddNum,orderStatus);
        shopId = hgMallOrdersPage.getRecords().get(0).getShopId();

        if (hgMallOrdersPage!=null){
            redisTemplate.opsForValue().set(key,hgMallOrdersPage,60, TimeUnit.MINUTES);
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrdersPage);
        }
        return R.error(HttpStatus.ORDER_ERROR,"查询错误");
    }



    /**
     * 查询订单详情
     */
    @GetMapping("/orderForm/{id}")
    public R<HgMallOrders> getInfo(@PathVariable("id") String id) {
        HgMallOrders hgMallOrders = null;
        redisTemplate.delete(id);
        hgMallOrders = (HgMallOrders) redisTemplate.opsForValue().get(id);
        if (hgMallOrders != null){
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrders);
        }
      hgMallOrders =  hgMallOrderService.selectHgMallOrdersForm(id);
      if (hgMallOrders!=null){
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrders);
      }
      return R.error(HttpStatus.ORDER_ERROR,"未查到当前用户");
    }

    /**
     * 根据id删除订单信息和子订单
     *
     * @param ids id
     * @return {@link R}
     */
    @DeleteMapping("/deleteOrder/{ids}")
    public R deleteByIds(@PathVariable String[] ids){
       int update=hgMallOrderService.deleteByIds(ids);
       if (update>0){
           redisTemplate.delete("order_" + shopId);
           return R.success(HttpStatus.ORDER_SUCCESS,"删除成功");
       }
            return R.error(HttpStatus.ORDER_ERROR,"删除失败");
    }


    /**
     * 更新订单
     *
     * @param hgMallOrders hg商城订单
     * @return {@link R}
     */
    @PutMapping("/updateOrder")
    public R updateOrders(@RequestBody HgMallOrders hgMallOrders){
       int updateOrder= hgMallOrderService.updateOrder(hgMallOrders);
       if (updateOrder==0){
           return R.error(HttpStatus.ORDER_ERROR,"修改失败");
       }
        redisTemplate.delete("order_" + shopId);
        return R.success(HttpStatus.ORDER_SUCCESS,"修改成功");
    }


    /**
     * 更新是否消费状态
     *
     * @param map 地图
     * @return {@link R}
     */
    @PutMapping("/updateStatus")
    public R updateStatus(@RequestBody HashMap<String,Object> map){
        String id = (String) map.get("id");
        int status = (int) map.get("status");
        int updateStatus=hgMallOrderService.updateStatus(id,status);
        if (updateStatus==0){
            return R.error(HttpStatus.ORDER_ERROR,"修改状态失败");
        }
        redisTemplate.delete("order_" + shopId);
        return R.success(HttpStatus.ORDER_SUCCESS,"修改状态成功");
    }

    /**
     * 更新是否通知取餐状态
     *
     * @param map 地图
     * @return {@link R}
     */
    @PutMapping("/updateMealStatus")
    public R updateMealStatus(@RequestBody HashMap<String,Object> map){
        String id = (String) map.get("id");
        int mealStatus = (int) map.get("mealStatus");
        int updateMealStatus=hgMallOrderService.updateMealStatus(id,mealStatus);
        if (updateMealStatus==0){
            return R.error(HttpStatus.ORDER_ERROR,"修改状态失败");
        }
        redisTemplate.delete("order_" + shopId);
        return R.success(HttpStatus.ORDER_SUCCESS,"修改状态成功");
    }

    /**
     * 将订单信息导出成excl表格
     *
     * @param response 响应
     * @throws Exception 异常
     */
    @GetMapping("/ordersExport")
    public void export(HttpServletResponse response) throws Exception {
        System.out.println("欢迎导出");
        // 从数据库查询出所有的数据
        List<HgMallOrders> list=hgMallOrderService.selectHgMAllOrdersAll();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "菜品ID");
        writer.addHeaderAlias("appid", "用户appid");
        writer.addHeaderAlias("shopId", "店铺id");
        writer.addHeaderAlias("status", "待完成");
        writer.addHeaderAlias("mealStatus", "取餐状态");
        writer.addHeaderAlias("orderDishVo", "菜品");
        writer.addHeaderAlias("oddNum", "订单号");
        writer.addHeaderAlias("orderNum", "取单号");
        writer.addHeaderAlias("priceAll", "priceAll");
        writer.addHeaderAlias("shopName", "店铺名字");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("菜品信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
}
